//
//  TravelsForThisSpotViewController.m
//  hai游～
//
//  Created by jakf_17 on 15/5/25.
//  Copyright (c) 2015年 jakf_17. All rights reserved.
//

#import "TravelsForThisSpotViewController.h"
#import <AFNetworking/AFNetworking.h>
#import "SpotImageCell.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "MJRefresh.h"
#import "RightTableView.h"
#import "TravelNotesDetailViewController.h"
@interface TravelsForThisSpotViewController ()<UITableViewDataSource, UITableViewDelegate>

@end

@implementation TravelsForThisSpotViewController


- (void)dealloc
{
    [_tableView release];
    [_scroll release];
    [_array release];
    [super dealloc];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    NSMutableArray *array = [NSMutableArray arrayWithObjects:@"游记", @"点评", nil];
    UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:array];
    seg.layer.cornerRadius = 14;
    seg.selectedSegmentIndex = 0;
    seg.frame = CGRectMake(([[UIScreen mainScreen] bounds].size.width - 175) / 2, 24, 175, 28);
    seg.layer.borderColor = [UIColor colorWithRed:216 / 255.0 green:33 / 255.0 blue:13 / 255.0 alpha:1].CGColor;
    seg.layer.borderWidth = 1;
    seg.layer.masksToBounds = YES;
    seg.backgroundColor = [UIColor colorWithRed:216 / 255.0 green:33 / 255.0 blue:13 / 255.0 alpha:1];
    seg.tintColor = [UIColor whiteColor];
    [seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = seg;
    self.scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, self.view.frame.size.height - 64)];
    self.scroll.contentSize = CGSizeMake([[UIScreen mainScreen] bounds].size.width * 2, self.view.frame.size.height - 64);
    self.scroll.scrollEnabled = NO;
    [self.view addSubview:_scroll];
    [_scroll release];
    [self createRightTableView];
    [self createTableView];
    [self loadDataSource];
    [self loadRightDataSource];
}
- (void)segAction:(UISegmentedControl *)sender
{
    if (sender.selectedSegmentIndex == 0) {
        _scroll.contentOffset = CGPointMake(0, 0);
    } else if (sender.selectedSegmentIndex == 1) {
        _scroll.contentOffset = CGPointMake([[UIScreen mainScreen] bounds].size.width, 0);
    }
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
    }
    return self;
}
- (void)createRightTableView
{
    self.rightView = [[RightTableView alloc] initWithFrame:CGRectMake([[UIScreen mainScreen] bounds].size.width, 0, [[UIScreen mainScreen] bounds].size.width, self.view.frame.size.height)];
    [self.scroll addSubview:_rightView];
    [_rightView release];
}
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    _tableView.separatorColor = [UIColor colorWithRed:220 / 255.0 green:220 / 255.0 blue:220 / 255.0 alpha:1];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.scroll addSubview:_tableView];
    
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(headerAction:)];
    
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(footerAction:)];
    [_tableView release];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _array.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:13]};
    NSDictionary *trips = _array[indexPath.row];
//    NSDictionary *trip = [trips objectForKey:@"trip"];
    NSString *content = [trips objectForKey:@"trip_text"];
    if (content != nil) {
        
        
        CGRect rect = [content boundingRectWithSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width - 10, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        return 136 + rect.size.height;
    } else {
        return 136;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellPool = @"cellPool";
    NSString *path = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:path];

    SpotImageCell *cell = [tableView dequeueReusableCellWithIdentifier:cellPool];
    if (cell == nil) {
        cell = [[[SpotImageCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellPool] autorelease];
    }
    NSDictionary *bigTrip = _array[indexPath.row];
    NSDictionary *trip = [bigTrip objectForKey:@"trip"];
    cell.label.text = [bigTrip objectForKey:@"trip_text"];
    cell.dateLabel.text = [trip objectForKey:@"datetime"];
    NSDictionary *user = [trip objectForKey:@"user"];
    NSString *avatar_s = [user objectForKey:@"avatar_l"];
    [cell.userImage sd_setImageWithURL:[NSURL URLWithString:avatar_s] placeholderImage:image];
    cell.userName.text = [user objectForKey:@"name"];
    cell.labelBlock = ^(NSInteger trip_id) {
        TravelNotesDetailViewController *detailNotes = [[TravelNotesDetailViewController alloc] init];
        detailNotes.webId = [NSString stringWithFormat:@"%ld", trip_id];
        [self.navigationController pushViewController:detailNotes animated:YES];
        [detailNotes release];
    };
    NSString *text = [trip objectForKey:@"name"];
    NSString *name = [NSString stringWithFormat:@"@%@", text];
    cell.userSum.text = name;
    NSArray *photoArray = [bigTrip objectForKey:@"waypoints"];
    cell.scroll.contentSize = CGSizeMake(115 * photoArray.count, 80);
    
    for (int i = 0; i < photoArray.count; i++) {
        NSDictionary *dic = photoArray[i];
        NSString *imagePath = [dic objectForKey:@"photo"];
        NSNumber *trip_id = [dic objectForKey:@"trip_id"];
        cell.userSum.tag = trip_id.integerValue;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * 115, 0, 110, 80)];
        [imageView sd_setImageWithURL:[NSURL URLWithString:imagePath] placeholderImage:image];
        [cell.scroll addSubview:imageView];
        [imageView release];
    }

    return cell;
}
#pragma mark - 下拉刷新数据
- (void)headerAction:(id)sender
{
    
        // 刷新
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    [manager.requestSerializer setValue:@"BreadTrip/android/5.1.0/zh (android OS4.4.4) lte26007 Map/GoogleMap/v1 (HM 2A,Xiaomi) Paros/3.2.13" forHTTPHeaderField:@"User-Agent"];
    NSString *webSite = [NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%@/%@/poi_trips/?start=0&count=5",self.model.type, self.model.destinationId];
    [manager GET:webSite parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        self.array = [NSMutableArray array];
        [self createArrayWithDic];
        [_tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
    }];

    //    [self.tableView reloadData];
    // 拿到当前的下拉刷新控件,结束下拉控件
    [self.tableView.header endRefreshing];
    
}


#pragma mark - 上拉加载数据
- (void)footerAction:(id)sender
{
//    NSString *path = [NSString stringWithFormat:@"http://api.breadtrip.com/v5/index/?next_start=%@",self.next_start];
    
//    [ConnectModle connectWithWebSite:path delegate:self];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    [manager.requestSerializer setValue:@"BreadTrip/android/5.1.0/zh (android OS4.4.4) lte26007 Map/GoogleMap/v1 (HM 2A,Xiaomi) Paros/3.2.13" forHTTPHeaderField:@"User-Agent"];
    NSString *webSite = [NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%@/%@/poi_trips/?start=%@&count=5",self.model.type, self.model.destinationId, self.next_start];
    [manager GET:webSite parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        [self createArrayWithDic];
        [_tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
    }];

    
    
    // 拿到当前的上拉加载控件,结束上拉控件
    [self.tableView.footer endRefreshing];
}

- (void)createArrayWithDic
{
    [self.array addObjectsFromArray:[_dic objectForKey:@"trips"]];
    self.next_start = [_dic objectForKey:@"next_start"];
}
- (void)loadDataSource
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    [manager.requestSerializer setValue:@"BreadTrip/android/5.1.0/zh (android OS4.4.4) lte26007 Map/GoogleMap/v1 (HM 2A,Xiaomi) Paros/3.2.13" forHTTPHeaderField:@"User-Agent"];
    NSString *webSite = [NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%@/%@/poi_trips/?start=0&count=5",self.model.type, self.model.destinationId];
    [manager GET:webSite parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        [self createArrayWithDic];
        [_tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
    }];
}
- (void)loadRightDataSource
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    [manager.requestSerializer setValue:@"BreadTrip/android/5.1.0/zh (android OS4.4.4) lte26007 Map/GoogleMap/v1 (HM 2A,Xiaomi) Paros/3.2.13" forHTTPHeaderField:@"User-Agent"];
    NSString *webSite = [NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%@/%@/tips/?start=0&count=20",self.model.type, self.model.destinationId];
    [manager GET:webSite parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        self.rightView.array = [dic objectForKey:@"tips"];
        [self.rightView.tableView reloadData];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
    }];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *bigTrip = _array[indexPath.row];
    NSArray *waypoints = [bigTrip objectForKey:@"waypoints"];
    NSDictionary *subDic = [waypoints firstObject];
    NSNumber *trip_id = [subDic objectForKey:@"trip_id"];
    TravelNotesDetailViewController *detailNotes = [[TravelNotesDetailViewController alloc] init];
    detailNotes.webId = [NSString stringWithFormat:@"%@", trip_id];
    [self.navigationController pushViewController:detailNotes animated:YES];
    [detailNotes release];
}
@end
